package com.fancy.application.common.utils;

import cn.hutool.core.util.ArrayUtil;
import lombok.SneakyThrows;
import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.Statements;
import net.sf.jsqlparser.statement.select.*;
import net.sf.jsqlparser.util.TablesNamesFinder;

import java.util.ArrayList;
import java.util.List;


public class SQLParseUtil {
//
    public static void main(String[] args) throws JSQLParserException {
        String sql = "select fd_name,fd_aaa as b from tt";
        List<String> items = SQLParseUtil.getColumns(sql);
        items.forEach(selectItem -> System.out.println(selectItem));

    }

    @SneakyThrows
    public static List<String> getColumns(String sql){
        Select statement = (Select) CCJSqlParserUtil.parse(sql);
        List<SelectItem> items = SQLParseUtil.getSelectItems(statement.getSelectBody());
        List<String> columnList = new ArrayList<>();
        items.forEach(selectItem -> {
            SelectExpressionItem expressionItem = (SelectExpressionItem) selectItem;
            if(expressionItem.getAlias()!=null){
                columnList.add(expressionItem.getAlias().getName());
            }else{
                columnList.add(expressionItem.getExpression().toString());
            }

        });
        return columnList;
    }

    /**
     * 获取查询字段
     * @param selectBody
     * @return
     */
    public static List<SelectItem> getSelectItems(SelectBody selectBody){
        List<SelectItem> selectItems = ((PlainSelect) selectBody).getSelectItems();
        return selectItems;
    }

}
